#include "parasettingdb.h"
#include <QDebug>
#include <QSqlError>

ParaSettingDB::ParaSettingDB(QObject *parent)
    : QObject(parent)
{
    Init();
}

Model *ParaSettingDB::getModel()
{
    return &m_Model;
}

void ParaSettingDB::updateModel()
{
    QSqlDatabase db = QSqlDatabase::database("my.db");
    QSqlQuery query(db);

	QString sql = QString("update parasetting set time = '%1', "
		"timeunit = '%2', shuffle = %3, start = %4 , auto = %5 "
		"where name = 'setting'")
		.arg(m_Model.strTime)
		.arg(m_Model.strTimeUnit)
		.arg(m_Model.bShuffle)
		.arg(m_Model.bStart)
		.arg(m_Model.bAuto);

    if(!query.exec(sql))
    {
        qDebug() << query.lastError();
    }
}

void ParaSettingDB::Init()
{
    QSqlDatabase db = QSqlDatabase::database("my.db");
    QSqlQuery query(db);

    bool result = query.exec(QString("select * from parasetting"));
	if (!result)
	{
		qDebug() << query.lastError();
	}
	else
	{
		if (query.next())
		{
			m_Model.strTime = query.value(1).toString();
			m_Model.strTimeUnit = query.value(2).toString();
			m_Model.bShuffle = query.value(3).toBool();
			m_Model.bStart = query.value(4).toBool();
			m_Model.bAuto = query.value(5).toBool();
		}
		else
		{
			result = query.exec(QString("insert into parasetting values( 'setting', %1, %2, %3, %4, %5)")
				.arg(m_Model.strTime)
				.arg(m_Model.strTimeUnit)
				.arg(m_Model.bShuffle)
				.arg(m_Model.bStart)
				.arg(m_Model.bAuto));

			if (!result)
			{
				qDebug() << query.lastError();
			}
		}
	}
}

